package com.fablesoft.projectdatacollect.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.MemberQueryBean;
import com.fablesoft.projectdatacollect.bean.MemberQueryListResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.view.MyRefreshListView;
import com.fablesoft.projectdatacollect.view.MyRefreshListView.RefreshListViewListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class RegisteredSearchActivity extends BaseRequestActivity implements OnClickListener, TextWatcher, TextView.OnEditorActionListener, RefreshListViewListener {

    private ArrayList<MemberQueryBean> memberQueryList = new ArrayList<>();
    ;
    private MyRefreshListView memberListView;
    private View noDataLayout;
    private View noDataTip;
    private View connectionFailedTip;
    private int pagesize = 10;
    private int page = 1;
    private static final int REFRESH_INFO_REQUEST_CODE = 101;
    private static final int INFO_REQUEST_CODE = 102;
    private static final int LOAD_INFO_REQUEST_CODE = 103;
    private View loadingLayout;
    private View loadingProgressbar;

    private EditText etSearch;
    private String searchParam;

    private String activityId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registered_search);
        activityId = getIntent().getStringExtra("id");
        initView();
    }

    private void initView() {
        memberListView = (MyRefreshListView) findViewById(R.id.member_list);
        noDataLayout = findViewById(R.id.no_data_reload_layout);
        noDataTip = findViewById(R.id.no_data_tip);
        connectionFailedTip = findViewById(R.id.connection_failed_tip);
        loadingLayout = findViewById(R.id.loading_layout);
        loadingProgressbar = findViewById(R.id.loading_progressbar);
        etSearch = (EditText) findViewById(R.id.et_search);
        etSearch.addTextChangedListener(this);
        etSearch.setOnEditorActionListener(this);
        View back = findViewById(R.id.back);
        View reloadBtn = findViewById(R.id.reload_btn);
        back.setOnClickListener(this);
        reloadBtn.setOnClickListener(this);
        memberListView.setAdapter(mAdapter);
        memberListView.setRefreshListViewListener(this);
        memberListView.setPullLoadEnable(false);
        memberListView.setPullRefreshEnable(false);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    private void showLoading() {
        if (loadingProgressbar != null) {
            Animation loadAnimation = AnimationUtils.loadAnimation(
                    RegisteredSearchActivity.this, R.anim.loading);
            loadingProgressbar.startAnimation(loadAnimation);
        }
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    private void dismissLoading() {
        if (loadingProgressbar != null) {
            loadingProgressbar.clearAnimation();
        }
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reload_btn:
                search();
                break;
            case R.id.back:
                finish();
                break;
            case R.id.bt_sign:
                jumpToPage(0, memberQueryList.get((Integer) v.getTag()));
                break;
            case R.id.bt_fingerprint:
                jumpToPage(1, memberQueryList.get((Integer) v.getTag()));
                break;
        }
    }

    private void jumpToPage(int flag, MemberQueryBean memberBean) {
        Intent intent = new Intent(RegisteredSearchActivity.this, SignFingerprintActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean("isRegister", true);
        bundle.putInt("flag", flag);
        bundle.putSerializable("member", memberBean);
        bundle.putString("id", activityId);
        intent.putExtra("data", bundle);
        startActivity(intent);
        finish();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 0) {
            etSearch.setHint(R.string.hint_print_name_or_cardid);
        }
    }

    class ViewHolder {
        TextView name;
        TextView post;
        TextView department;
        TextView sign;
        TextView fingerprint;
    }

    private BaseAdapter mAdapter = new BaseAdapter() {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(RegisteredSearchActivity.this).inflate(
                        R.layout.item_registered_search, null);
                viewHolder.name = (TextView) convertView
                        .findViewById(R.id.name);
                viewHolder.post = (TextView) convertView
                        .findViewById(R.id.post);
                viewHolder.department = (TextView) convertView
                        .findViewById(R.id.department);
                viewHolder.sign = (TextView) convertView
                        .findViewById(R.id.bt_sign);
                viewHolder.fingerprint = (TextView) convertView
                        .findViewById(R.id.bt_fingerprint);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
//            if (viewHolder.sign.getTag() != null && position == (Integer) viewHolder.sign.getTag()) {
//                return convertView;
//            }
            MemberQueryBean member = memberQueryList.get(position);
            viewHolder.name.setText(member.getPersonName());
            viewHolder.sign.setTag(position);
            viewHolder.fingerprint.setTag(position);
            viewHolder.post.setText(member.getPostName());
            viewHolder.department.setText(member.getDepartmentName());
            viewHolder.sign.setOnClickListener(RegisteredSearchActivity.this);
            viewHolder.fingerprint.setOnClickListener(RegisteredSearchActivity.this);
            return convertView;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public int getCount() {
            return memberQueryList.size();
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_INFO_REQUEST_CODE:
                    updateRefreshData(msg.obj);
                    break;
                case LOAD_INFO_REQUEST_CODE:
                    updateLoadData(msg.obj);
                    break;
                case INFO_REQUEST_CODE:
                    updateData(msg.obj);
                    break;
            }
        }

        ;
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    ;

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void showNoDataTip() {
        noDataTip.setVisibility(View.VISIBLE);
        connectionFailedTip.setVisibility(View.GONE);
        noDataLayout.setVisibility(View.VISIBLE);
        memberListView.setVisibility(View.GONE);
    }

    private void showconnectionFailedTip() {
        noDataTip.setVisibility(View.GONE);
        connectionFailedTip.setVisibility(View.VISIBLE);
        noDataLayout.setVisibility(View.VISIBLE);
        memberListView.setVisibility(View.GONE);
    }

    private void loginExpire() {
        dismissLoading();
        noDataTip.setVisibility(View.GONE);
        connectionFailedTip.setVisibility(View.GONE);
        noDataLayout.setVisibility(View.VISIBLE);
        memberListView.setVisibility(View.GONE);
    }

    private void updateData(Object data) {
        // memberList.clear();
        if (data == null) {
            Toast.makeText(RegisteredSearchActivity.this, R.string.request_error,
                    Toast.LENGTH_SHORT).show();
            showconnectionFailedTip();
        } else {
            MemberQueryListResponse memeberListResponse = (MemberQueryListResponse) data;
            if (memeberListResponse.getRows() != null) {
                if (memberListView == null) {
                    return;
                }
                if (memeberListResponse.getRows().size() == 0) {
                    showNoDataTip();
                } else {
                    memberQueryList.clear();
                    memberQueryList.addAll(memeberListResponse.getRows());
                    mAdapter.notifyDataSetChanged();
                    noDataLayout.setVisibility(View.GONE);
                    memberListView.setVisibility(View.VISIBLE);
                }
            } else {
                showNoDataTip();
            }
        }
        dismissLoading();
    }

    private void updateLoadData(Object data) {
        if (data == null) {
            Toast.makeText(RegisteredSearchActivity.this, R.string.request_error,
                    Toast.LENGTH_SHORT).show();
        } else {
            MemberQueryListResponse memberListResponse = (MemberQueryListResponse) data;
            if (memberListResponse.getRows() != null) {
                if (memberListResponse.getRows().size() == 0) {
                    memberListView.setNoDataLoad();
                } else {
                    if (memberListResponse.getRows().size() == pagesize) {
                        memberListView.setPullLoadEnable(true);
                    }
                    memberQueryList.addAll(memberListResponse.getRows());
                    mAdapter.notifyDataSetChanged();
                    noDataLayout.setVisibility(View.GONE);
                    memberListView.setVisibility(View.VISIBLE);
                }
            } else {
                memberListView.setNoDataLoad();
            }
        }
        memberListView.stopLoadMore();
    }

    private void updateRefreshData(Object data) {
        if (data == null) {
            Toast.makeText(RegisteredSearchActivity.this, R.string.request_error,
                    Toast.LENGTH_SHORT).show();
        } else {
            MemberQueryListResponse memberListResponse = (MemberQueryListResponse) data;
            if (memberListResponse.getRows() != null) {
                if (memberListResponse.getRows().size() != 0) {
                    ArrayList<MemberQueryBean> temp = new ArrayList<>();
                    temp.addAll(memberListResponse.getRows());
                    temp.addAll(memberQueryList);
                    memberQueryList.clear();
                    memberQueryList = null;
                    memberQueryList = temp;
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
        memberListView.stopRefresh();
    }

    @Override
    public void onRefresh() {
        if (searchParam == null) {
            memberQueryList.clear();
            mAdapter.notifyDataSetChanged();
            return;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        params.put("size", pagesize);
        params.put("page", page);
        param.put("name", searchParam);
        params.put("mapParams", param);
        HttpThread httpThread = new HttpThread(Config.CAMPAIGN_QUERY_REGISTER_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = REFRESH_INFO_REQUEST_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                        loginExpire();
                        RegisteredSearchActivity.this.onNotLogin(response);
                    }
                }, params, MemberQueryListResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    @Override
    public void onLoadMore() {
        page++;
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        params.put("size", pagesize);
        params.put("page", page);
        param.put("name", searchParam);
        params.put("mapParams", param);
        HttpThread httpThread = new HttpThread(Config.CAMPAIGN_LIST_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = LOAD_INFO_REQUEST_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                        loginExpire();
                        RegisteredSearchActivity.this.onNotLogin(response);
                    }
                }, params, MemberQueryListResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    @Override
    public void onRequestFinish(BaseResponse response) {
        Message msg = mHandler.obtainMessage();
        msg.obj = response;
        msg.what = INFO_REQUEST_CODE;
        mHandler.sendMessage(msg);
    }

    ;

    @Override
    public void onNotLogin(BaseResponse response) {
        loginExpire();
        super.onNotLogin(response);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            search();
            CommonUtils.hideSoftKeyboard(this);
            return true;
        }
        return false;
    }

    private void search() {
        searchParam = etSearch.getText().toString();
        if (searchParam == null || searchParam == "") {
            return;
        }
        // 搜索请求
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        params.put("size", pagesize);
        params.put("page", page);
        param.put("name", searchParam);
        params.put("mapParams", param);
        showLoading();
        sendRequest(Config.CAMPAIGN_QUERY_REGISTER_URL, params, MemberQueryListResponse.class);
    }

}
